package com.etc.rabbitmq;

import com.etc.dao.FlashGoodsStockDao;
import com.etc.entity.FlashGoodsStock;
import com.etc.entity.FlashOrder;
import com.etc.entity.User;
import com.etc.redis.FlashGoodsKey;
import com.etc.redis.RedisService;
import com.etc.result.CodeMsg;
import com.etc.result.Result;
import com.etc.service.impl.FlashOrderServiceImpl;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 文件名:com.etc.rabbitmq
 * 描述：消息的接受者，处理秒杀业务
 * 作者:吴仕泉
 * 时间:2019/5/24 0:57
 */
@Service
public class MQReceiver {

    @Autowired
    RedisService redisService;

    @Autowired
    FlashGoodsStockDao flashGoodsStockDao;

    @Autowired
    FlashOrderServiceImpl flashOrderService;

    @RabbitListener(queues=MQExchang.Flash_QUEUE)
    public void receive(String message) {

        FlashMessage fm = RedisService.stringToBean(message, FlashMessage.class);
       // System.out.println("Receiver:"+fm);

        //从数据库中获取库存商品库存
        FlashGoodsStock fgs = flashGoodsStockDao.getFlashGoodsStockByFlashGoodsId(fm.getFlashGoodsId());
         if(fgs.getStocknum()<=fgs.getSellnum()+fm.getGoodsNum()){
            return ;
        }
        //判断是否已秒杀到
        FlashOrder fo = redisService.get(FlashGoodsKey.getFlashGoodsOrder,fm.getUserId()+":"+fm.getFlashGoodsId(), FlashOrder.class);
        if(fo != null){
            return ;
        }
        //下订单减库存写入秒杀订单
       boolean flag =  flashOrderService.PlaceAndOrder(fm);
        if(flag){
            redisService.set(FlashGoodsKey.getSignFlashOrder,fm.getUserId()+":"+fm.getFlashGoodsId(),1);

           // FlashOrder f = redisService.get(FlashGoodsKey.getFlashGoodsOrder,fm.getUserId()+":"+fm.getFlashGoodsId(), FlashOrder.class);
           // System.out.println("下单成功:"+f);
        }else{
            //下单失败
            redisService.set(FlashGoodsKey.getSignFlashOrder,fm.getUserId()+":"+fm.getFlashGoodsId(),2);

        }
     }
}
